<?php

require_once('php/XDomainProxy.php');


$_XDomain_Proxy = new XDomainProxy();


if (isset( $_GET['cache_clear'] )) {
    $_XDomain_Proxy->cache->clear();
    exit;
}

// ---------------------------------------------
//
//        WikiPedia Awesome Proxy  v0.2
//
//
//    [Based on]     PHP v5.3+
//
//    [Thank for]    WikiWand,  EasyLibs.php
//
//    [License]      Public Domain
//
// ---------------------------------------------

$_Proxy_Host = 'http://www.wikiwand.com';

$_Path_Info = isset( $_SERVER['PATH_INFO'] )  ?  $_SERVER['PATH_INFO']  :  '/';


$_JavaScript = <<<JS
<script>
    $(document).on('click',  'a',  function () {
        $(this).attr('href',  function () {
            switch (arguments[1][0]) {
                case '/':    return arguments[1].slice(1);
                case '#':    return (
                    self.location.href.slice( $('base[href]')[0].href.length )  +  arguments[1]
                );
            }
        });
    });
</script>
JS;

$_XDomain_Proxy->onLoad('GET',  '/',  function ($_HTML, $_Header) use ($_Proxy_Host, $_JavaScript) {
    if ($_Header['Response-Code'] == 302) {
        $_Header['Location'] = $_SERVER['SCRIPT_NAME'].$_Header['Location'];

        return  array('header' => $_Header);
    }
    return array(
        'header'  =>  array(),
        'data'    =>  trim(preg_replace(
            array(
                '/\.googleapis\.com/',
                '#</head>#',
                '#zh\.(wikipedia\.org/w/api\.php)#',
                "#/(api/[^/'\"]+)#",
                '#(<script>window\.location[^/]+)/#',
                '/\n\s*\n\s*\n/'
            ),
            array(
                '.useso.com',
                "    <base href=\"{$_SERVER['SCRIPT_NAME']}/\" />\n{$_JavaScript}\n$0",
                'en.$1',
                "{$_Proxy_Host}/$1",
                '$1',
                "\n\n"
            ),
            $_HTML
        ))
    );
})->open("{$_Proxy_Host}{$_Path_Info}", 86400)->send();